package com.sinan.core.connector.components;

import com.sinan.core.connector.ValidationResult;
import com.sinan.core.connector.exception.PropertyInValidException;

import java.util.Map;

/**
 * @author pengpei
 * @date 2025-06-10
 */
public class StandardPropertyContext implements PropertyContext {
    private final Map<String, String> properties;

    public StandardPropertyContext(Map<String, String> properties) {
        this.properties = properties;
    }

    @Override
    public PropertyValue getProperty(PropertyDescriptor descriptor) {
        String name = descriptor.getName();
        String configuredValue = properties.get(name);
        String rawValue = configuredValue == null ? descriptor.getDefaultValue() : configuredValue.trim();

        // 验证值
        if (rawValue == null || rawValue.isEmpty()) {
            if (descriptor.isRequired()) {
                throw new PropertyInValidException(String.format("%s is required", name));
            }
        }
        for (Validator validator : descriptor.getValidators()) {
            ValidationResult validationResult = validator.validate(name, rawValue);
            if (!validationResult.isValid()) {
                throw new PropertyInValidException(validationResult.getExplanation());
            }
        }
        return new StandardPropertyValue(rawValue);
    }
}
